import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.ImageWindow;
import ij.process.StackConverter;
import util.QualityControlHelper;

/**
 * This plugin creates a median image from an image stack.  It first converts
 * the stack to 8 bit grayscale, and then finds the median at each pixel location
 * to produce the median image.
 */
public class Median_Image {

    public Median_Image() {
        this(WindowManager.getCurrentImage());
    }
    
    public Median_Image(ImagePlus img) {
        
        if(img == null) {
            IJ.noImage();
            return;
        }
        
        if(img.getNSlices() < 2) {
            IJ.error("Median Image plugin must be run on a stack");
            return;
        }
        
        if(img.getType() != ImagePlus.GRAY8) {
            StackConverter sc = new StackConverter(img);
            sc.convertToGray8();
        }
        
        String fileName = img.getOriginalFileInfo().fileName;
        if (fileName.isEmpty()) { //fileName can be empty if we are using a newly created median image
            fileName = img.getTitle();
        }
        
        ImagePlus medianImg = QualityControlHelper.getMedianImageFromStack(img.getImageStack(), fileName);
        ImageWindow window = new ImageWindow(medianImg);
        WindowManager.setCurrentWindow(window);
    }
}
